import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.IOException;
import java.util.Map;

public class HttpClient {

    private static final String HTML_SUFFIX = ".html";

    private static HttpGet createHttpRequest(Map<String, String> map, String url) {
        HttpGet httpGet = new HttpGet(url);
        for (String key : map.keySet()) {
            httpGet.addHeader(StringUtils.removeEnd(key, ":"), map.get(key));
        }
        return httpGet;
    }

    public static JSONObject sendRequest(Map<String, String> map, String url) throws IOException {
        HttpGet httpGet = createHttpRequest(map, url);

        // 创建 HttpClient 实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 发送请求
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String responseBody = EntityUtils.toString(entity, "UTF-8");
            return JSON.parseObject(responseBody);
        } catch (IOException e) {
            // 处理异常并抛出
            throw new IOException("Error during HTTP request: " + e.getMessage(), e);
        }
    }

    public static void generateHtml(JSONObject object, String path) throws IOException {
        JSONArray data = object.getJSONArray("data");
        for (Object o : data) {
            JSONObject jsonObject = (JSONObject) o;

            // 获取问题标题
            JSONObject questionObject = (JSONObject) jsonObject.get("question");
            String title = questionObject.get("title").toString().replaceAll("[?、╲/*\"<>|]", "");

            // 获取回答内容并格式化
            Object content = jsonObject.get("content");
            content = "<html><body>" + content + "</body></html>";

            // 使用 Jsoup 解析并修正 HTML 内容
            Document document = Jsoup.parse(content.toString());
            String fixedContent = document.html();

            // 生成文件路径
            File file = new File(path + File.separator + title + HTML_SUFFIX);
            file.getParentFile().mkdirs();  // 确保目录存在
            file.deleteOnExit();
            file.createNewFile();

            // 使用 FileUtils 写入文件
            FileUtils.write(file, fixedContent, "UTF-8");
        }
    }
}
